import React, { Component } from "react";
import { withRouter } from "../../router/hooks";
import "./swipe.less";

class Swipe extends Component {
  constructor(props) {
    super(props);
    this.state = {
      indicator: [],
      swipeValue: 0,
    };
  }
  render() {
    const slot = this.props.slot;
    return (
      <div
        className="swipe"
        style={{ display: this.props.length > 0 ? "block" : "none" }}
      >
        <div
          className="swipe_content"
          style={{
            width: this.props.length * 330 + "px",
            transform: "translateX(-" + this.state.swipeValue * 330 + "px)",
          }}
        >
          {slot}
        </div>
        <div
          className="swipe_indicator"
          style={{ display: this.props.length > 1 ? "flex" : "none" }}
        >
          {this.state.indicator.map((v, index) => {
            return (
              <i
                key={v}
                className={this.state.swipeValue === index ? "on" : ""}
              ></i>
            );
          })}
        </div>
      </div>
    );
  }
  componentDidMount() {
    let arr = [],
      self = this;
    for (let i = 0; i < this.props.length; i++) {
      arr.push(i);
    }
    this.setState({ indicator: [...arr] });

    if (this.props.length > 1) {
      let n = 0;
      let timeout = setInterval(() => {
        n += 1;
        if (n > self.props.length - 1) {
          n = 0;
        }
        self.setState({ swipeValue: n });
      }, 2000);

      this.setState({ timeout: timeout });
    }
  }
  componentWillUnmount() {
    clearInterval(this.state.timeout);
    this.setState({ timeout: null });
  }
}

export default withRouter(Swipe);
